import prisma from '@/server/lib/prisma';
import { encryptAES } from '@/server/lib/md5';
import { signToken } from '@/server/lib/jwt';

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { userName, password } = body;

    const user = await prisma.sys_user.findMany({
      where: {
        userName,
        password: encryptAES(password),
      },
    });

    if (Array.isArray(user) && user.length === 0) {
      return {
        code: 400,
        msg: '用户名或者密码有误',
      };
    } else {
      return {
        code: 200,
        msg: '登录成功',
        data: signToken(userName),
      }
    }
  } catch (e) {
    throw e;
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})